package per.hx.bs.web.sys.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import per.hx.bs.base.BaseController;
import per.hx.bs.base.annotation.BsCLog;
import per.hx.bs.base.domain.Tree;
import per.hx.bs.base.domain.ReturnDTO;
import per.hx.bs.entity.sys.SysFileDO;
import per.hx.bs.entity.sys.SysMenuDO;
import per.hx.bs.shiro.ShiroUser;
import per.hx.bs.util.BuildTree;
import per.hx.bs.util.ShiroUtils;
import per.hx.bs.util.ValidateCode;
import per.hx.bs.web.sys.service.SysFileService;
import per.hx.bs.web.sys.service.SysMenuService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author HuXing
 * @date 2018/3/11  12:41
 */
@Controller
public class LoginController extends BaseController {


    private final
    SysMenuService sysMenuService;

    private final
    SysFileService sysFileService;

    @Autowired
    public LoginController(SysMenuService sysMenuService, SysFileService sysFileService) {
        this.sysMenuService = sysMenuService;
        this.sysFileService = sysFileService;
    }

    @GetMapping(value = {"/", ""})
    public String welcome() {
        return "redirect:/index";
    }

    @GetMapping(value = "login")
    public String login() {
        ShiroUser name = ShiroUtils.getUser();
        if (name != null) {
            return "redirect:index";
        }
        return "login";
    }

    @GetMapping(value = "validateCode")
    public void validateCode(HttpServletResponse response) {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        Session session = SecurityUtils.getSubject().getSession();
        ValidateCode vCode = new ValidateCode(120, 40, 5, 100);
        session.setAttribute("validateCode", vCode.getCode().toLowerCase());
        System.out.println(vCode.getCode().toLowerCase());
        try {
            vCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @BsCLog("登录认证")
    @PostMapping(value = "/ajaxLogin")
    @ResponseBody
    public ReturnDTO ajaxLogin(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String username,
                               @RequestParam(FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM) String password,
                               @RequestParam("validateCode") String validateCode) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        System.out.println(validateCode);
        Session session = SecurityUtils.getSubject().getSession();
        String vCode = (String) session.getAttribute("validateCode");
        if (!vCode.equals(validateCode.toLowerCase())) {
            Subject subject = SecurityUtils.getSubject();
            try {
                subject.login(token);
                return ReturnDTO.ok("登录成功");
            } catch (UnknownAccountException e) {
                return ReturnDTO.error(e.getLocalizedMessage());
            } catch (DisabledAccountException e) {
                return ReturnDTO.error(e.getLocalizedMessage());
            } catch (IncorrectCredentialsException e) {
                return ReturnDTO.error("密码错误");
            }
        } else {
            return ReturnDTO.error("验证码错误");
        }
    }


    @BsCLog("请求访问主页")
    @GetMapping(value = "/index")
    public String index(Model model) {

        List<Tree<SysMenuDO>> menus = sysMenuService.listMenuTree(getUserId());

        model.addAttribute("menus", BuildTree.buildList(menus, "0"));
        model.addAttribute("name", getName());
        SysFileDO fileDO = null;
        if (getUser().getPicId() != null) {
            fileDO = sysFileService.get(getUser().getPicId());

        }

        if (fileDO != null && fileDO.getUrl() != null) {
            if (sysFileService.isExist(fileDO.getUrl())) {
                model.addAttribute("picUrl", fileDO.getUrl());
            } else {
                model.addAttribute("picUrl", "/img/HuXingBs-Defualt.gif");
            }
        } else {
            model.addAttribute("picUrl", "/img/HuXingBs-Defualt.gif");
        }
        model.addAttribute("userName", getUserName());
        return "index";
    }

    @GetMapping(value = "main")
    public String main() {
        return "main";
    }

    @BsCLog("topSearch")
    @PostMapping(value = "index")
    public String index(String topSearch, Model model) {

        if (topSearch != null) {
            List<SysMenuDO> sysMenuDOS = sysMenuService.searchByName(topSearch);
            if (!sysMenuDOS.isEmpty()) {
                if (sysMenuDOS.get(0).getUrl() != null && !"".equals(sysMenuDOS.get(0).getUrl())) {
                    return "redirect:" + sysMenuDOS.get(0).getUrl();
                }
            }
        }
        index(model);
        return "index";

    }

    @GetMapping(value = "/403")
    public String noPermissions() {

        return "/error/403";
    }

}
